﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lead2012.Business;
using Lead2012.Models;
using Lead2012.ViewModels;
using Lead2012.Repository;

namespace Lead2012.Controllers
{
    public class FieldSetupController : BaseController
    {
        // Create an instance of repository
        FieldManagementRepository repository = new FieldManagementRepository();

        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            FieldViewModel model = new FieldViewModel();

            // Setup model
            model.PageType = "Menu";
            SetupCommon(model, string.Empty, "Name");
            repository.GetModel(model);

            return View(model);
        }

        // Add new group, section
        [HttpPost]
        public ActionResult AddNewGroupSection(int id, string title, string type)
        {
            FieldGroupRepository repository = new FieldGroupRepository();
            FieldGroup model = new FieldGroup();

            if (type == "group")
            {
                model.OrderId = repository.GetAllByParentId(0).Count + 1;
                model.ParentId = 0;
                model.Title = title;
                repository.Create(model);
            }
            else if (type == "section")
            {
                model.OrderId = repository.GetAllByParentId(id).Count + 1;
                model.ParentId = id;
                model.Title = title;
                repository.Create(model);
            }
            else
            {
                if (id > 0)
                {
                    model = repository.GetSingle(id);
                    model.Title = title;
                    repository.Update(model);
                }
            }
            

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        // Add new fields
        [HttpPost]
        public ActionResult AddNewField(int id, string title, int fieldTypeId, int leadTypeId, int visibilityId, int groupId, int sectionId, string toolTip, bool required, bool printable, bool filterable)
        {
            FieldCustomRepository fcRepository = new FieldCustomRepository();
            FieldCustom fcModel = new FieldCustom();
            FieldRepository fRepository = new FieldRepository();
            Field fModel = new Field();

            if (id > 0)
            {
                // Update field custom table
                fcModel = fcRepository.GetSingle(id);

                // fcModel.FieldId = id;
                fcModel.ToolTip = toolTip;
                fcModel.LenderSafe = false;
                fcModel.Required = required;
                fcModel.Printable = printable;
                fcModel.Filterable = filterable;
                fcModel.VisibilityId = visibilityId;
                if (sectionId > 0)
                    groupId = sectionId;
                //fcModel.GroupId = groupId;
                fcRepository.Update(fcModel, groupId);

                // Update field table
                fModel = fRepository.GetSingle(id);
                fModel.Title = title;
                fModel.Description = toolTip;
                fRepository.Update(fModel, fieldTypeId);

                // Update lead form type
                FieldCustomLeadFormTypeRepository fclftRepository = new FieldCustomLeadFormTypeRepository();
                FieldCustomLeadFormType fclftModel = new FieldCustomLeadFormType();
                fclftRepository.Delete(id);

                if (leadTypeId > 0)
                {
                    fclftModel.FieldId = id;
                    fclftModel.TypeId = leadTypeId;
                    fclftRepository.Create(fclftModel);
                }

            }
            else
            {
                // Add field custom table
                fcModel.ToolTip = toolTip;
                fcModel.Required = required;
                fcModel.Printable = printable;
                fcModel.LenderSafe = false;
                fcModel.Filterable = filterable;
                fcModel.VisibilityId = visibilityId;
                if (sectionId > 0)
                    groupId = sectionId;
                fcModel.GroupId = groupId;

                var list = fcRepository.GetAllByGroup(groupId);
                if (list != null && list.Count > 0)
                    fcModel.OrderId = list.LastOrDefault().OrderId + 1;

                fcRepository.Create(fcModel);

                // Add field table
                fModel.FieldId = fcModel.FieldId;
                fModel.Title = title;
                fModel.Description = toolTip;
                fModel.TypeId = fieldTypeId;
                fRepository.Create(fModel);

                // Add column
                LeadWarehouseManagementRepository lwRepository = new LeadWarehouseManagementRepository();
                lwRepository.AddColumn(string.Format("f{0}", fModel.FieldId));

                // Add lead form type
                if (leadTypeId > 0)
                {
                    FieldCustomLeadFormTypeRepository fclftRepository = new FieldCustomLeadFormTypeRepository();
                    FieldCustomLeadFormType fclftModel = new FieldCustomLeadFormType();
                    fclftRepository.Delete(fModel.FieldId);
                    fclftModel.FieldId = fModel.FieldId;
                    fclftModel.TypeId = leadTypeId;
                    fclftRepository.Create(fclftModel);
                }
            }

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult GetFieldInfo(int id)
        {
            FieldTypeGroupInfo model = new FieldTypeGroupInfo();
            model = repository.GetFieldTypeGroupInfo(id);

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        // Delete Group/ Field
        [HttpPost]
        public ActionResult DeleteGroup(int id)
        {
            FieldGroupRepository repository = new FieldGroupRepository();
            repository.Delete(id);

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult DeleteField(int id)
        {
            FieldRepository fRepository = new FieldRepository();
            FieldCustomRepository fcRepository = new FieldCustomRepository();

            fRepository.Delete(id);
            fcRepository.Delete(id);

            // Delete column
            LeadWarehouseManagementRepository lwRepository = new LeadWarehouseManagementRepository();
            lwRepository.DeleteColumn(string.Format("f{0}", id));

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdateVisible(int id)
        {
            string message = string.Empty;
            FieldCustom model = new FieldCustom();
            FieldCustomRepository fcRepository = new FieldCustomRepository();

            model = fcRepository.GetSingle(id);

            if (model.VisibilityId == -1)
            {
                model.VisibilityId = 0;
                message = "No";
            }
            else if (model.VisibilityId == 0)
            {
                model.VisibilityId = 1;
                message = "Yes";
            }
            else if (model.VisibilityId == 1)
            {
                model.VisibilityId = -1;
                message = "Read-only";
            }

            fcRepository.Update(model);

            return Json(message, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdatePrintable(int id)
        {
            string message = string.Empty;
            FieldCustom model = new FieldCustom();
            FieldCustomRepository fcRepository = new FieldCustomRepository();

            model = fcRepository.GetSingle(id);

            if (model.Printable == true)
            {
                model.Printable = false;
                message = "No";
            }
            else
            {
                model.Printable = true;
                message = "Yes";
            }

            fcRepository.Update(model);

            return Json(message, JsonRequestBehavior.AllowGet);
        }

        // Items
        [HttpPost]
        public ActionResult GetItemByField(int id)
        {
            FieldItemManagementRepository repository = new FieldItemManagementRepository();
            var list = repository.GetAllItemByField(id);

            return Json(list, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult AddNewItems(int id, string title)
        {
            FieldItemManagementRepository repository = new FieldItemManagementRepository();
            FieldItem model = new FieldItem();
            List<FieldItemInfo> list = repository.GetAllItemByField(id);

            model.FieldId = id;
            model.Title = title;
            model.OrderId = list.Count + 1;
            repository.Create(model);

            list = repository.GetAllItemByField(id);

            return Json(list, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult DeleteItems(int id)
        {
            FieldItemManagementRepository repository = new FieldItemManagementRepository();
            FieldItem model = new FieldItem();
            List<FieldItemInfo> list = repository.GetAllItemByField(id);

            model = repository.GetSingle(id);
            repository.Delete(id);

            list = repository.GetAllItemByField(model.FieldId);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdateItems(int id, string order)
        {
            FieldItemManagementRepository repository = new FieldItemManagementRepository();
            FieldItem model = new FieldItem();
            List<FieldItemInfo> list = new List<FieldItemInfo>();

            // Get current field id
            model = repository.GetSingle(id);
            int fieldId = model.FieldId;

            list = repository.GetAllItemByField(fieldId);
            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Id == id)
                    {
                        if (order == "up")
                        {
                            // Set order current item
                            model.OrderId -= 1;
                            repository.Update(model);

                            // Set order prev item
                            model = new FieldItem();
                            model = repository.GetSingle(list[i - 1].Id);
                            model.OrderId += 1;
                            repository.Update(model);
                        }
                        else
                        {
                            // Set order current item
                            model.OrderId += 1;
                            repository.Update(model);

                            // Set order prev item
                            model = new FieldItem();
                            model = repository.GetSingle(list[i + 1].Id);
                            model.OrderId -= 1;
                            repository.Update(model);                            
                        }
                        break;
                    }
                }
            }

            list = repository.GetAllItemByField(fieldId);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdateOrderGroupFieldItems(int id, string type, string order)
        {
            if (type == "group" || type == "section")
            {
                UpdateOrderGroup(id, order);
            }
            else
            {
                UpdateOrderFields(id, order);
            }

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        #region Order Items
        private void UpdateOrderGroup(int id, string order)
        {
            FieldGroupRepository repository = new FieldGroupRepository();
            FieldGroup model = new FieldGroup();

            model = repository.GetSingle(id);

            if (model != null)
            {
                int parentId = (model.ParentId != null && model.ParentId.HasValue) ? model.ParentId.Value : 0;
                var list = repository.GetAllByParentId(parentId);
                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i].GroupId == id)
                        {
                            // Up
                            if (order == "up")
                            {
                                // Update current group
                                model.OrderId -= 1;
                                repository.Update(model);

                                // Update prev group
                                model = repository.GetSingle(list[i - 1].GroupId);
                                model.OrderId += 1;
                                repository.Update(model);
                            }
                            else if (order == "down")
                            {
                                // Update current group
                                model.OrderId += 1;
                                repository.Update(model);

                                // Update prev group
                                model = repository.GetSingle(list[i + 1].GroupId);
                                model.OrderId -= 1;
                                repository.Update(model);
                            }

                            break;
                        }
                    }
                }
            }
        }
        
        private void UpdateOrderFields(int id, string order)
        {
            FieldCustomRepository repository = new FieldCustomRepository();
            FieldCustom model = new FieldCustom();

            model = repository.GetSingle(id);

            if (model != null)
            {
                var list = repository.GetAllByGroup(model.GroupId);
                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        /*
                        model = repository.GetSingle(list[i].FieldId);
                        model.OrderId = i + 1;
                        repository.Update(model);
                        */

                        if (list[i].FieldId == id)
                        {
                            // Up
                            if (order == "up")
                            {
                                // Update current group
                                model.OrderId = i;
                                repository.Update(model);

                                // Update prev group
                                model = repository.GetSingle(list[i - 1].FieldId);
                                model.OrderId = i + 1;
                                repository.Update(model);
                            }
                            else if (order == "down")
                            {
                                // Update current group
                                model.OrderId = i + 1;
                                repository.Update(model);

                                // Update prev group
                                model = repository.GetSingle(list[i + 1].FieldId);
                                model.OrderId = i;
                                repository.Update(model);
                            }

                            break;
                        }
                    }
                }
            }
        }
        #endregion
    }
}
